package main

import (
	"Godzilla/common/etcd"
	"Godzilla/common/responses"
	"Godzilla/conf/databases"
	"Godzilla/enum/code"
	"Godzilla/routes"
	"Godzilla/websockets"
	"context"
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"log"
	"net/http"
	"time"
)



func main()  {

	e := echo.New()
	e.Use(middleware.Logger())

	//读取mysql配置
	databases.MysqlSetConfig()
	//读取redis配置
	databases.RedisSetConfig()
	//读取etcd配置
	databases.EtcdSetConfig()


	//user路由
	userRoute := e.Group("/user")
	routes.UserGroupRoute(userRoute)

	//role路由
	roleRoute := e.Group("/role")
	routes.RoleGroupRoute(roleRoute)

	//router路由
	routerRoute := e.Group("/router")
	routes.RouterGroupRoute(routerRoute)

	//user-role 路由
	userRoleRouter := e.Group("/user-role")
	routes.UserRoleGroupRoute(userRoleRouter)

	//role-router路由
	roleRouterRouter := e.Group("/role-router")
	routes.RoleRouterGroupRoute(roleRouterRouter)

	e.Use(middleware.Recover())
	e.Static("/", "../public")
	e.GET("/ws", websockets.Doing)


	//查找websocket中连接的用户id
	e.POST("/connect", func(c echo.Context) error {
		ids :=  websockets.GetClientMaps()
		if ids == nil {
			ids = []int64{}//空数组
		}
		return c.JSON(http.StatusOK, responses.Response(200, "成功", ids))
	})

	//删除etcd
	e.POST("/etcd", func(c echo.Context) error {

		//etcd
		cli, err := etcd.NewEtcdCli()
		if err != nil {
			log.Println(err.Error())
		}
		defer cli.Close()

		ctx, _ := context.WithTimeout(context.Background(), 5 * time.Second)

		//_, err = cli.Put(ctx, "/inline/test2", "test111")
		//if err != nil {
		//	log.Println(err.Error())
		//}
		result, err := cli.Get(ctx, "/inline/1")
		if err != nil {
			log.Println(err.Error())
		}
		log.Println("etcd")

		for _, ev := range result.Kvs {
			fmt.Printf("%s : %s\n", ev.Key, ev.Value)
		}
		//
		//_, err = cli. Delete(ctx, "/inline/test2")
		return c.JSON(http.StatusOK, responses.Response(200, "成功", ""))
	})

	//文件上传
	//e.POST("/upload", UploadFile)
	e.GET("/error", func(c echo.Context) error {
		return c.JSON(http.StatusOK, responses.Response(code.PermissionError, "token有误", ""))
	})


	//生产路由url 请求方法json文件
	//data, err := json.MarshalIndent(e.Routes(), "", "  ")
	//if err != nil {
	//	log.Println(err.Error())
	//}
	//ioutil.WriteFile("routes.json", data, 0644)


	e.Start(":8081")

}
